"""
通用响应模式
"""

from pydantic import BaseModel, Field
from typing import Optional, Any, List, Dict, Generic, TypeVar
from datetime import datetime

T = TypeVar('T')


class BaseResponse(BaseModel, Generic[T]):
    """基础响应模式"""
    success: bool = Field(..., description="是否成功")
    message: str = Field(..., description="响应消息")
    data: Optional[T] = Field(None, description="响应数据")
    timestamp: datetime = Field(default_factory=datetime.now, description="响应时间")


class SuccessResponse(BaseResponse[T]):
    """成功响应模式"""
    success: bool = Field(default=True, description="是否成功")
    
    @classmethod
    def create(cls, data: T = None, message: str = "操作成功"):
        return cls(success=True, message=message, data=data)


class ErrorResponse(BaseResponse[None]):
    """错误响应模式"""
    success: bool = Field(default=False, description="是否成功")
    error_code: Optional[str] = Field(None, description="错误代码")
    error_details: Optional[Dict[str, Any]] = Field(None, description="错误详情")
    
    @classmethod
    def create(cls, message: str, error_code: str = None, error_details: Dict[str, Any] = None):
        return cls(
            success=False, 
            message=message, 
            error_code=error_code,
            error_details=error_details
        )


class PaginationInfo(BaseModel):
    """分页信息模式"""
    page: int = Field(..., ge=1, description="当前页码")
    page_size: int = Field(..., ge=1, le=100, description="每页大小")
    total: int = Field(..., ge=0, description="总记录数")
    total_pages: int = Field(..., ge=0, description="总页数")
    has_next: bool = Field(..., description="是否有下一页")
    has_prev: bool = Field(..., description="是否有上一页")


class PaginatedResponse(BaseModel, Generic[T]):
    """分页响应模式"""
    success: bool = Field(default=True, description="是否成功")
    message: str = Field(default="查询成功", description="响应消息")
    data: List[T] = Field(..., description="数据列表")
    pagination: PaginationInfo = Field(..., description="分页信息")
    timestamp: datetime = Field(default_factory=datetime.now, description="响应时间")
    
    @classmethod
    def create(cls, data: List[T], page: int, page_size: int, total: int, message: str = "查询成功"):
        total_pages = (total + page_size - 1) // page_size
        pagination = PaginationInfo(
            page=page,
            page_size=page_size,
            total=total,
            total_pages=total_pages,
            has_next=page < total_pages,
            has_prev=page > 1
        )
        return cls(
            success=True,
            message=message,
            data=data,
            pagination=pagination
        )


class StatusResponse(BaseModel):
    """状态响应模式"""
    status: str = Field(..., description="状态")
    message: str = Field(..., description="状态消息")
    details: Optional[Dict[str, Any]] = Field(None, description="状态详情")
    timestamp: datetime = Field(default_factory=datetime.now, description="响应时间")


class HealthCheckResponse(StatusResponse):
    """健康检查响应模式"""
    services: Dict[str, str] = Field(..., description="服务状态")
    version: str = Field(..., description="系统版本")
    uptime: str = Field(..., description="运行时间")


class ValidationErrorResponse(ErrorResponse):
    """验证错误响应模式"""
    validation_errors: List[Dict[str, Any]] = Field(..., description="验证错误详情")
    
    @classmethod
    def create(cls, validation_errors: List[Dict[str, Any]], message: str = "数据验证失败"):
        return cls(
            success=False,
            message=message,
            error_code="VALIDATION_ERROR",
            validation_errors=validation_errors
        )


class AuthErrorResponse(ErrorResponse):
    """认证错误响应模式"""
    auth_required: bool = Field(default=True, description="是否需要认证")
    login_url: Optional[str] = Field(None, description="登录URL")
    
    @classmethod
    def create(cls, message: str = "认证失败", login_url: str = None):
        return cls(
            success=False,
            message=message,
            error_code="AUTH_ERROR",
            auth_required=True,
            login_url=login_url
        )


class RateLimitResponse(ErrorResponse):
    """限流错误响应模式"""
    retry_after: int = Field(..., description="重试等待时间（秒）")
    limit: int = Field(..., description="限制次数")
    remaining: int = Field(..., description="剩余次数")
    
    @classmethod
    def create(cls, retry_after: int, limit: int, remaining: int, message: str = "请求过于频繁"):
        return cls(
            success=False,
            message=message,
            error_code="RATE_LIMIT",
            retry_after=retry_after,
            limit=limit,
            remaining=remaining
        )


class BusinessErrorResponse(ErrorResponse):
    """业务错误响应模式"""
    business_code: str = Field(..., description="业务错误代码")
    suggestions: Optional[List[str]] = Field(None, description="解决建议")
    
    @classmethod
    def create(cls, business_code: str, message: str, suggestions: List[str] = None):
        return cls(
            success=False,
            message=message,
            error_code="BUSINESS_ERROR",
            business_code=business_code,
            suggestions=suggestions or []
        )


# 常用的响应类型别名
UserResponse = SuccessResponse[Dict[str, Any]]
MonitorResponse = SuccessResponse[Dict[str, Any]]
NotificationResponse = SuccessResponse[Dict[str, Any]]
BalanceResponse = SuccessResponse[Dict[str, Any]]
